<!--
 * @Descripttion: 员工与部门管理
 * @version: @ 1.0.0
 * @Author: ZJZ
 * @Date: 2021-06-09 14:06:05
 * @LastEditors: 朱江洲
 * @LastEditTime: 2022-05-17 17:37:19
-->
<template>
  <div class="app-container">
    <div class="left">
      <div class="left-title">
        <img src="@/assets/images/icon-guanli.png" alt="" />
        <span>员工与部门管理</span>
      </div>
      <div class="company" style="overflow: auto">
        <el-tree
          :data="data"
          accordion
          :props="defaultProps"
          @node-click="handleNodeClick"
          highlight-current
        >
          <template slot-scope="{ node, data }">
            <el-tooltip
              effect="dark"
              :content="node.label"
              placement="top-start"
            >
              <div class="tool">
                <span class="comName">
                  {{ node.label }}
                </span>
                <div class="set">
                  <el-dropdown style="margin-left: 10px">
                    <el-button class="el-icon-more"></el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item
                        @click.native="addDept(data)"
                        v-hasPermi="['system:dept:add']"
                      >
                        新增部门
                      </el-dropdown-item>
                      <el-dropdown-item
                        @click.native="editDept(node, data)"
                        v-hasPermi="['system:dept:edit']"
                      >
                        编辑
                      </el-dropdown-item>
                      <el-dropdown-item
                        @click.native="delDept(data)"
                        v-hasPermi="['system:dept:remove']"
                      >
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </div>
            </el-tooltip>
          </template>
        </el-tree>
      </div>
    </div>
    <div class="right">
      <div class="head">
        <div class="det">
          {{ comName }}
        </div>
        <div class="search">
          <el-input
            v-model="input"
            placeholder="请输入姓名/手机号码"
            size="normal"
            clearable
            style="width: 266px; height: 36px"
          ></el-input>
          <el-button type="primary" size="default" @click="search">
            搜索
          </el-button>
        </div>
      </div>
      <div class="btn">
        <div class="but-left" v-if="chioose">
          <span>场景：</span>
          <el-select
            v-model="value"
            placeholder="全部"
            clearable
            filterable
            class="sel"
            @change="senceSearch"
          >
            <el-option
              v-for="(item, index) in options"
              :key="index"
              :label="item.label"
              :value="item.status"
            >
            </el-option>
          </el-select>
        </div>
        <div v-else>
          <el-button
            type="primary"
            size="default"
            @click="edit"
            plain
            :disabled="disabled"
          >
            编辑
          </el-button>
          <el-button
            type="primary"
            size="default"
            @click="batchExport"
            plain
            v-hasPermi="['system:user:exportByIds']"
          >
            批量导出
          </el-button>
          <!-- <el-button
            type="primary"
            size="default"
            @click="reset"
            plain
            :disabled="disabled"
          >
            重置密码
          </el-button> -->
          <el-button
            type="danger"
            size="default"
            @click="del"
            v-if="drawerData.isAdmin !== 1"
            plainÎ
          >
            删除
          </el-button>
        </div>
        <div class="btn-right">
          <el-button
            type="primary"
            size="default"
            @click="addStaff"
            v-hasPermi="['system:user:add']"
          >
            新增员工
          </el-button>
          <el-dropdown style="margin-left: 10px">
            <el-button class="el-icon-more"></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                @click.native="importStaff"
                v-hasPermi="['system:user:import']"
                >导入员工</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <el-table
        :data="adminData"
        @selection-change="handleSelectionChange"
        :height="tableHight"
      >
        <template slot="empty" class="emptyBg">
          <img src="@/assets/images/empty.jpg" alt="" />
        </template>
        <el-table-column type="selection"> </el-table-column>
        <el-table-column label="姓名" :show-overflow-tooltip="true" fixed>
          <template slot-scope="scope">
            <span class="admin" @click="drawer(scope.row)">
              {{ scope.row.nickName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="手机号"
          prop="phonenumber"
          width="120"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column label="性别" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ scope.row.sex == 0 ? "男" : "女" }}
          </template>
        </el-table-column>
        <el-table-column
          label="部门"
          prop="dept.deptName"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column label="直属上司" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ scope.row.parentName ? scope.row.parentName : "-" }}
          </template>
        </el-table-column>
        <el-table-column label="状态" v-hasPermi="['system:user:changeStatus']">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
              :disabled="scope.row.isAdmin == 1 ? true : false"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="是否激活">
          <template slot-scope="scope">
            {{ scope.row.active == 1 ? "未激活" : "激活" }}
          </template>
        </el-table-column>
        <el-table-column label="角色" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ scope.row.isAdmin == 1 ? "管理员" : scope.row.roleNames }}
          </template>
        </el-table-column>
        <el-table-column label="职位" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ scope.row.post != null ? scope.row.post : "-" }}
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        prev-text="上一页"
        next-text="下一页"
        background
        :page-size="pageSize"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        layout=" ->,total, sizes, prev, pager, next, jumper "
        :total="total"
      >
      </el-pagination>
    </div>
    <admin-drawer
      :dialog="dialog"
      :drawerData="drawerData"
      v-if="dialog.eject"
    ></admin-drawer>
    <admin-department :dialog="dialog"></admin-department>
    <admin-staff
      :dialog="dialog"
      :staffFrom="staffFrom"
      ref="adminStaff"
    ></admin-staff>
    <!--  v-if="dialog.ejectStaff" -->
    <el-dialog
      title="重置密码"
      :visible.sync="dialog.resetPsd"
      width="30%"
      @close="resetClose"
      custom-class="dialogClass"
      :close-on-click-modal="false"
    >
      <el-form
        :model="resetForm"
        ref="resetForm"
        :rules="resetRules"
        label-width="80px"
      >
        <el-form-item label="账号">
          <el-input
            v-model="resetForm.account"
            style="width: 266px"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码">
          <el-input
            v-model="resetForm.password"
            style="width: 266px"
          ></el-input>
          <div class="tip">
            密码必须包含数字、小写字母、大写字母 且长度不低于6位
          </div>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input
            v-model="resetForm.confirmPsd"
            style="width: 266px"
          ></el-input>
          <div class="redTip">
            注：重置密码后请将新密码告知员工，确保员工正常使用！
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialog.resetPsd = false">取消</el-button>
        <el-button type="primary" @click="resetSubmit">保存</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="deptShow ? '新增部门' : '编辑部门'"
      :visible.sync="dialog.newDept"
      width="30%"
      @close="newDeptClose"
      custom-class="dialogClass"
      :close-on-click-modal="false"
    >
      <el-form
        :model="deptForm"
        ref="deptForm"
        :rules="deptRules"
        label-position="top"
        style="margin-left: 30px"
        v-if="dialog.newDept"
      >
        <el-form-item label="上级部门" prop="parentId">
          <el-select v-model="deptForm.parentId" style="width: 330px">
            <el-option
              v-for="item in detData"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门名称" prop="deptName">
          <el-input
            v-model="deptForm.deptName"
            placeholder="请输入部门名称"
            style="width: 330px"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialog.newDept = false">取消</el-button>
        <el-button type="primary" @click="newDeptSubmit" v-if="deptShow">
          保存
        </el-button>
        <el-button type="primary" @click="editDeptSubmit" v-else
          >保存</el-button
        >
      </span>
    </el-dialog>
    <div class="importInfo" v-if="dialogImportEject">
      <el-dialog
        title="员工导入"
        :visible.sync="dialogImport"
        width="50%"
        custom-class="dialogClass"
        :close-on-click-modal="false"
        @close="exportClose"
      >
        <div class="module">
          <div class="module-txt">
            1.<span style="color: #1267fa">下载</span
            >部门与员工信息模版，填写模版信息
          </div>
          <div class="module-img">
            <img src="@/assets/images/download.png" alt="" />
            <el-button round style="" @click="downloadTemplate">
              下载模板
            </el-button>
          </div>
        </div>
        <div class="dashed"></div>
        <div class="module">
          <div class="module-txt">
            2.<span style="color: #1267fa">上传</span>填写好的部门与员工信息文件
          </div>
          <div class="module-img">
            <img src="@/assets/images/upload.png" alt="" />
            <el-upload
              class="upload-demo"
              ref="uploadDept"
              action="#"
              :limit="1"
              accept=".xlsx,.xls"
              :http-request="httpRequest"
              :on-change="handleChange"
              :on-success="handleSuccess"
            >
              <el-button class="taskBtn" round> 上传文件 </el-button>
            </el-upload>
          </div>
        </div>
        <span slot="footer">
          <div>
            <span class="font-txt">
              注：
              导入会覆盖原有部门与员工的信息，如需更新已存在的员工，请先导出通讯录，在导出表格里进行修改
            </span>
          </div>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getTreeselect,
  getList,
  getDeptList,
  newDept,
  delDept,
  editDept,
  delUser,
  putPsd,
  changeStatus,
  importTemplateUser,
  importData,
  exportByIds,
} from "@/api/sys";
import AdminDepartment from "./conponments/adminDepartment.vue";
import adminDrawer from "./conponments/adminDrawer.vue";
import AdminStaff from "./conponments/adminStaff.vue";
import { mapGetters } from "vuex";
export default {
  components: { adminDrawer, AdminDepartment, AdminStaff },
  data() {
    return {
      tableHight: window.innerHeight - 330,
      options: [
        {
          label: "激活",
          status: 0,
        },
        {
          label: "冻结",
          status: 1,
        },
      ],
      deptId: "", // 部门id
      dialogImport: false, //
      dialogImportEject: false,
      deptShow: true,
      userIds: [],
      comName: "",
      active: 1,
      input: "",
      value: "",
      total: 0,
      pageSize: 10,
      pageNum: 1,
      chioose: true,
      disabled: false,
      staffFrom: {
        isAdmin: "",
        userId: "",
        nickName: "",
        phonenumber: "",
        password: "",
        confirmPassword: "",
        email: "",
        sex: "",
        deptId: "",
        roleIds: [],
        parentId: "",
        post: "", // 职务
      },
      drawerData: {},
      // 所有部门及公司集合
      detData: [],
      // 新增部门规则
      deptRules: {
        parentId: [
          { required: true, message: "请选择上级部门", trigger: "change" },
        ],
        deptName: [
          {
            required: true,
            message: "请输入部门名称",
            trigger: "blur",
          },
        ],
      },
      // 新增部门
      deptForm: {
        parentId: "",
        deptName: "",
        deptId: "",
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      data: [],
      resetRules: {},
      resetForm: {
        userId: "",
        account: "",
        password: "",
        confirmPsd: "",
      },
      dialog: {
        dialogAdminShow: false,
        dialogDepartmentShow: false,
        dialogStaffShow: false,
        resetPsd: false,
        newDept: false,
        eject: false,
        ejectStaff: false,
      },
      adminData: [],
    };
  },
  watch: {
    input(newValue, oldValue) {
      if (newValue == "") {
        this.getList(this.deptId);
      }
    },
  },
  computed: {
    ...mapGetters(["loading"]),
  },
  created() {
    this.getTree();
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        this.tableHight = window.innerHeight - 330;
      })();
    };
  },
  activated() {
    this.tableHight = window.innerHeight - 330;
  },
  methods: {
    // 关闭
    exportClose() {
      this.dialogImportEject = false;
    },
    senceSearch() {
      this.getList(this.deptId);
    },

    // 上传成功
    handleSuccess(file) {
      console.log(1);
      // this.$refs["uploadDept"].clearFiles();
    },
    // 上传文件
    handleChange(file) {
      console.log(file);
    },
    httpRequest(data) {
      let { file } = data;
      console.log(file);
      var fd = new FormData();
      fd.append("file", file);
      fd.append("deptId", this.deptId);
      importData(fd).then((res) => {
        if (res.code !== 200) return this.$refs["uploadDept"].clearFiles();
        this.$message.success(res.msg);
        this.getList(this.deptId);
        this.dialogImport = true;
      });
    },
    // 下载模版
    downloadTemplate() {
      importTemplateUser().then((res) => {
        this.download(res.msg);
      });
    },
    // 切换状态
    handleStatusChange(row) {
      let text = row.status === "0" ? "激活" : "停用";
      this.$confirm(
        '确认要"' + text + '""' + row.nickName + '"用户吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return changeStatus({
            userId: row.userId,
            status: row.status,
          });
        })
        .then((res) => {
          if (res.code == 500) {
            this.getTree();
            return this.$message.info(res.msg);
          }

          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 导入员工
    importStaff() {
      this.dialogImportEject = true;
      this.$nextTick(() => {
        this.dialogImport = true;
      });
    },
    // 删除用户
    async del() {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该员工, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      /*如果用户确认打印confirm,如果用户取消显示cancel*/
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除!");
      } else {
        delUser(this.userIds).then((res) => {
          this.$message.success(res.msg);
          this.getTree();
        });
      }
    },
    // 确定编辑部门
    editDeptSubmit() {
      editDept(this.deptForm).then((res) => {
        if (res.code == 500) return this.$message.info(res.msg);
        this.$message.success(res.msg);
        this.dialog.newDept = false;
        this.getTree();
        console.log(this.$refs);
        this.$refs.adminStaff.getOrList();
      });
    },
    // 编辑部门
    editDept(node, data) {
      this.dialog.newDept = true;
      this.deptShow = false;
      this.deptForm.parentId = node.parent.data.id;
      this.deptForm.deptId = data.id;
      getDeptList().then((res) => {
        this.detData = res.data;
      });
    },
    // 删除部门
    async delDept(data) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该部门, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      /*如果用户确认打印confirm,如果用户取消显示cancel*/
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除!");
      } else {
        delDept({
          deptId: data.id,
        }).then((res) => {
          if (res.code == 500) return this.$message.info(res.msg);
          this.$message.success(res.msg);
          this.getTree();
        });
      }
      // console.log('确认了删除')
    },

    // 关闭新增部门
    newDeptClose() {
      this.deptShow = true;
      this.deptForm = {
        parentId: "",
        deptName: "",
      };
    },
    // 确定新增部门
    newDeptSubmit() {
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return;
        newDept(this.deptForm).then((res) => {
          this.$message.success(res.msg);
          this.getTree();
          this.dialog.newDept = false;
          this.$refs.adminStaff.getOrList();
        });
      });
    },

    // 打开新增部门
    addDept(val) {
      this.dialog.newDept = true;
      this.deptForm.parentId = val.id;
      getDeptList().then((res) => {
        this.detData = res.data;
      });
    },
    // 获取人员列表
    getList(id) {
      getList({
        status: this.value,
        identification: this.input,
        deptId: id,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      }).then((res) => {
        this.adminData = res.rows;
        this.total = res.total;
      });
    },
    // 树形结构点击事件
    handleNodeClick(val) {
      this.getList(val.id);
      this.deptId = val.id;
      this.comName = val.label;
    },
    // 获取权限树
    getTree() {
      getTreeselect().then((res) => {
        this.data = res.data;
        if (res.data.length > 0) {
          //'nextTick()' 下次dom更新时触发回调函数
          //默认点击
          this.$nextTick().then(() => {
            const firstNode = document.querySelector(".el-tree-node");
            firstNode.click();
          });
        }
      });
    },
    // 重置密码确认
    resetSubmit() {
      putPsd(this.resetForm).then((res) => {
        this.$message.success(res.msg);
        this.dialog.resetPsd = false;
      });
    },
    // 重置密码关闭dialog
    resetClose() {
      this.resetForm = {
        userId: "",
        account: "",
        password: "",
        confirmPsd: "",
      };
    },
    // 搜索
    search() {
      this.getList(this.deptId);
    },
    // 编辑
    edit() {
      this.dialog.ejectStaff = true;
      this.$nextTick(function () {
        this.dialog.dialogStaffShow = true;
        this.staffFrom.isAdmin = this.drawerData.isAdmin;
        this.staffFrom.userId = this.drawerData.userId;
        this.staffFrom.nickName = this.drawerData.nickName;
        this.staffFrom.phonenumber = this.drawerData.phonenumber;
        this.staffFrom.password = this.drawerData.password;
        this.staffFrom.confirmPassword = this.drawerData.password;
        this.staffFrom.email = this.drawerData.email;
        this.staffFrom.sex = this.drawerData.sex - 0;
        this.staffFrom.deptId = this.drawerData.dept.deptId;
        this.staffFrom.roleIds = this.drawerData.roleIds;
        this.staffFrom.parentId = this.drawerData.parentId;
        this.staffFrom.post = this.drawerData.post;
      });
    },
    // 批量导出
    batchExport() {
      exportByIds(this.userIds).then((res) => {
        this.download(res.msg);
      });
    },
    // 重置密码
    reset() {
      this.dialog.resetPsd = true;
    },
    // 新增员工
    addStaff() {
      this.dialog.ejectStaff = true;
      this.$nextTick(function () {
        this.dialog.dialogStaffShow = true;
      });
    },
    drawer(row) {
      this.drawerData = row;
      this.dialog.eject = true;
      this.$nextTick(function () {
        this.dialog.dialogAdminShow = true;
      });
    },
    handleSelectionChange(val) {
      if (val.length !== 0) {
        this.drawerData = val[0];
        let arr = [];
        val.forEach((item) => {
          arr.push(item.userId);
          this.userIds = arr;
        });
        this.resetForm.account = val[0].phonenumber;
        this.resetForm.userId = val[0].userId;
      }
      if (val.length >= 1) {
        this.chioose = false;
      } else {
        this.chioose = true;
      }
      if (val.length >= 2) {
        this.disabled = true;
      } else {
        this.disabled = false;
      }
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getList();
    },
  },
};
</script>

<style lang="less" scoped>
.app-container {
  height: 93vh;
  display: flex;
  width: 100%;
  .left {
    min-width: 20%;
    height: 100%;
    border-right: 1px solid #ececec;
    .company {
      height: 100%;
      overflow: auto;
    }
    .left-title {
      padding-top: 20px;
      width: 100%;
      height: 74px;
      border-bottom: 1px solid #ececec;
      img {
        margin-right: 10px;
        vertical-align: middle;
      }
    }
  }
  .right {
    width: 80%;
    height: 100%;
    .head {
      display: flex;
      width: 100%;
      height: 74px;
      border-bottom: 1px solid #ececec;
      align-items: center;
      .det {
        padding-left: 20px;
      }
      .search {
        margin: 0 auto;
      }
    }
    .btn {
      padding-left: 20px;
      margin-top: 23px;
      display: flex;
      justify-content: space-between;
    }
  }
}
.el-pagination {
  margin-top: 24px;
  /deep/ .el-pagination__total {
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    margin-right: 25px;
  }
  /deep/ .btn-prev {
    width: 80px;
    height: 40px;
    text-align: center;
  }
  /deep/ .btn-next {
    width: 80px;
    height: 40px;
    text-align: center;
  }
  /deep/ .number {
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
  }
  /deep/ .el-input__inner {
    // width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
  }
  /deep/ .more {
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
  }
  /deep/ .el-pagination__jump {
    .el-input__inner {
      width: 40px;
      height: 40px;
    }
  }
}
.admin {
  color: #1267fa;
}
.tip {
  margin-top: 10px;
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #3d4966;
}
.redTip {
  margin-top: 10px;
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #e02020;
}
.active {
  color: #1267fa !important;
}
/deep/.el-tree-node {
  margin-top: 20px;
  .el-tree-node__content {
    width: 100%;
    height: 48px;
  }
}
.tool {
  display: flex;
  justify-content: space-around;
  .comName {
    width: 100px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .el-button--medium {
    display: none;
    margin-left: 60px;
    border: 0;
  }
}
.el-tree-node__content:hover .el-button--medium {
  display: block;
}
.importInfo {
  /deep/.el-dialog__footer {
    text-align: left;
  }
  /deep/ .el-dialog__body {
    display: flex;
    justify-content: space-around;
    .module {
      width: 40%;
      height: 300px;
      .module-img {
        width: 49px;
        height: 60px;
        margin: 50%;
        transform: translate(-50%, -50%);
        img {
          width: 100%;
          height: 100%;
        }
        .el-button {
          margin-top: 10px;
          transform: translateX(-25%);
        }
      }

      .module-txt {
        transform: translateY(400%);
        text-align: center;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #1f2e4d;
      }
    }
  }
  .dashed {
    width: 1px;
    height: 180px;
    border-left: 2px dashed rgba(0, 0, 0, 0.1);
    transform: translateY(35%);
  }
  /deep/.el-upload-list {
    display: none;
  }
}
</style>